from django import forms
from django.core.exceptions import ValidationError
from django.db.models import F
from django.shortcuts import render, redirect
from django.db import transaction
from django_redis import get_redis_connection
from django.conf import settings
import datetime
import random
from django.contrib import messages
from django.conf import settings

from app01 import models
from app01.utils.script.pager import Paginator
from app01.utils.script.bootstrap import BootStrapForm



def order(request):
    queryset = models.Order.objects.filter(customer_id=request.user.id,active=1).order_by("-id")
    pager = Paginator(request,queryset)
    return render(request,"my_order.html",{"pager": pager})


class  MyOrderForm(BootStrapForm,forms.ModelForm):
    class Meta:
        model = models.Order
        fields = ['url','count']
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        queryset = models.PricePolicy.objects.all().order_by("count")
        price_count_list = []
        txt_count_list = []

        for item in queryset:
            unit_price = item.price / item.count
            txt_count_list.append(">={} ￥{}元/条".format(item.count,unit_price))
            price_count_list.append([item.count, ">={} ￥{}元/条".format(item.count,unit_price),unit_price])

        if txt_count_list:
            self.fields['count'].help_text = "、 ".join(txt_count_list)
        else:
            self.fields['count'].help_text = "请联系管理员设置价格"

        self.price_count_list = price_count_list
    def clean_count(self):
        count = self.cleaned_data['count']
        if not self.price_count_list:
            raise ValidationError("请联系管理员设置价格")
        min_count = self.price_count_list[0][0]
        if count < min_count:
            raise ValidationError("最低支持数量是：{}".format(min_count))
        return count


def order_add(request):
    if request.method == 'GET':
        form = MyOrderForm()
        return render(request,"form.html",{"form":form})

    form = MyOrderForm(data=request.POST)
    if not form.is_valid():
        return render(request,"form.html",{"form":form})

    video_url = form.cleaned_data['url']
    count = form.cleaned_data['count']

    from app01.utils.script.video import get_old_view_count
    status,old_view_count = get_old_view_count(video_url)
    print(status)
    if not status:
        form.add_error('url',"视频获取失败")
        return render(request,"form.html",{"form":form})

    for idx in range(len(form.price_count_list)-1,-1,-1):
        lim_count,_,unit_price = form.price_count_list[idx]
        if count >= lim_count:
            break
    total_price = count * unit_price
    print(total_price)

    # 产生订单
    try:
        with transaction.atomic():
            customer_obj = models.Customer.objects.filter(id=request.user.id,active=1).select_for_update().first()
            real_price = total_price * customer_obj.leval.present / 100
            print(customer_obj.balance)
            print("dddd")
            print("dddd",customer_obj.leval.present)
            if real_price > customer_obj.balance:
                form.add_error('count',"余额不足")
                return render(request,"form.html",{"form":form})
            #生成订单号
            while True:
                random_num = random.randint(100000,999999)
                cim = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")

                oid = "{}{}".format(cim, random_num)
                exists = models.Order.objects.filter(oid=oid).exists()
                if exists:
                    continue
                break

            form.instance.oid = oid
            form.instance.price = total_price
            form.instance.real_price = real_price
            form.instance.old_view_count = old_view_count
            form.instance.customer_id = request.user.id
            form.save()
            models.Customer.objects.filter(id=request.user.id,active=1).update(balance=F("balance") - real_price)
            models.TransactionRecord.objects.create(
                charge_type=3,
                customer_id=request.user.id,
                amount=real_price,
                order_oid=oid)
            conn = get_redis_connection("order")
            conn.lpush(settings.QUEUE_TASK_NAME, oid)
    except Exception as e:
        form.add_error('count', "创建订单失败 {}".format(e))
        return render(request,"form.html",{"form": form})
    return redirect("/my/order/list/")

def order_cancel(request, pk):
    ord_obj = models.Order.objects.filter(id=pk, active=1, status=1,customer_id=request.user.id).first()
    if not ord_obj:
        messages.add_message(request, settings.MESSAGE_DANGER, "订单不存在")
        return redirect("/my/order/list/")
    try:
        with transaction.atomic():
            #1.更改状态
            models.Order.objects.filter(id=pk, active=1, status=1,customer_id=request.user.id).update(status=5)
            #2.退钱
            models.Customer.objects.filter(id=request.user.id).update(balance=F("balance") + ord_obj.real_price)
            #3.交易记录
            models.TransactionRecord.objects.create(
                charge_type=5,
                customer_id=request.user.id,
                amount=ord_obj.real_price,
                order_oid=ord_obj.oid)
            messages.add_message(request, messages.SUCCESS, "撤单成功")
            return redirect("/my/order/list/")
    except:
        messages.add_message(request, settings.MESSAGE_DANGER, "撤单失败")
        return redirect("/my/order/list/")













